package api

import (
	"log"
	"net/http"
	"strconv"

	"gitee.com/d-fw/gofw-cache/internal/cache"
)

func DelCache(w http.ResponseWriter, c *cache.Cache, params []string) {
	if ok := c.Delete(params[4]); ok {
		log.Println("delete key value success")
		_, _ = w.Write(SuccessResult(""))
	} else {
		log.Println("delete key value fail")
		_, _ = w.Write(FailResult(""))
	}
}

func SetCache(w http.ResponseWriter, params []string, c *cache.Cache) {
	var ok bool
	if len(params) == 6 {
		ok = c.Set(params[4], params[5])
	} else if len(params) == 7 {
		ttl, _ := strconv.ParseInt(params[6], 10, 64)
		ok = c.Set(params[4], params[5], ttl)
	}
	if ok {
		log.Println("set key value success")
		_, _ = w.Write(SuccessResult(""))
	} else {
		log.Println("set key value fail")
		_, _ = w.Write(FailResult(""))
	}
}

func GetCache(w http.ResponseWriter, c *cache.Cache, params []string) {
	if value, err := c.Get(params[4]); err != nil {
		log.Println("get key value fail")
		_, _ = w.Write(FailResult(err.Error()))
	} else {
		log.Println("get key value success")
		_, _ = w.Write(SuccessResult(value))
	}
}

func NoCache(w http.ResponseWriter, params []string) {
	log.Println("no such cache: " + params[2])
	_, _ = w.Write(FailResult("no such cache: " + params[2]))
}

func PingCache(w http.ResponseWriter) {
	_, _ = w.Write(SuccessResult(""))
}
